package _6_13;

import java.nio.charset.StandardCharsets;

public class HexConverter {

    // 十六进制字符表
    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    /** 字符串转十六进制 */
    public static String strToHex(String str) {
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8); //所有数据地产都是字节，可以直接转16进制
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            // 127   -1   有符号的 &oxff    八位二进制的。每四位组成一个十六进制
            int v = b & 0xFF;  //b是带符号的，需要转为无符号的
            hex.append(HEX_ARRAY[v >>> 4]);
            hex.append(HEX_ARRAY[v & 0x0F]);
        }
        return hex.toString();
    }

    /** 十六进制转字符串 */
    public static String hexToStr(String hex) {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException("Hex字符串长度必须为偶数");
        }
        int len = hex.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            int high = hexCharToInt(hex.charAt(i));
            int low = hexCharToInt(hex.charAt(i + 1));
            //high需要向左移动四位
            bytes[i / 2] = (byte) ((high << 4) + low);
        }
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /** 辅助函数：单个16进制字符转int */
    private static int hexCharToInt(char c) {
        if (c >= '0' && c <= '9') return c - '0';
        if (c >= 'A' && c <= 'F') return c - 'A' + 10;
        if (c >= 'a' && c <= 'f') return c - 'a' + 10;
        throw new IllegalArgumentException("非法十六进制字符: " + c);
    }

    public static void main(String[] args) {
        String original = "Hello世界!";
        String hex = strToHex(original);
        String restored = hexToStr(hex);

        System.out.println("原始字符串: " + original);
        System.out.println("转为16进制: " + hex);
        System.out.println("还原字符串: " + restored);
    }
}
